﻿log("Running New Hub Client ... ");

const ADDON_CHANNEL = -1;
const HUB_CHANNEL = -2;

var TServer = {};

document.body.lastChild.textContent += "\nProgram is Running!";

initMessenger();
initTServer();

// ------------------------
// Initializations
// ------------------------

function initMessenger()
{
    self.port.on('hub', onHubMessage);
    self.port.on('log', onLogMessage);
}

function initTServer()
{
    const READY = 0;
    const CONNECTING = 1;
    const CONNECTED = 2;
    const RECONNECTING = 3;

    var ws;
    var state = READY;

    TServer.send = function (channel, type, arg)
    {
        log("---- >> Send message to TServer : " + "(channel " + channel + ")" + type);

        // Before sending to TServer, conversion from object to JSON is needed.
        var str = JSON.stringify({ channel: channel, type: type, arg: arg });
        return ws.send(str);
    };

    function connect()
    {
        log('Connecting to TServer ...');
        state = CONNECTING;
        ws = new WebSocket("ws://localhost:5666/", "protocolThirteen");

        ws.onopen = onOpen;
        ws.onmessage = onMessage;
        ws.onclose = onError;
        ws.onerror = onError;
    }

    function onOpen()
    {
        state = CONNECTED;
        log('>----<  Connected to TServer !!!');

        // Whenever connected, send a message to TServer to 
        // notify it that we are here.
        TServer.send(HUB_CHANNEL/*Any channel is ok*/, "mainClientLogin", { browser: "firefox" });
    }
    function onMessage(event)
    {
        var data = JSON.parse(event.data);

        var channel = data.channel;
        var type = data.type;
        var arg = data.arg;

        onServerMessage(channel, type, arg);
    };

    function onError()
    {
        if (state === RECONNECTING)
            return;
        state = RECONNECTING;
        log('Connection problem! Retry in 3s later ...');
        setTimeout(connect, 3000);
    }
    connect();
}

function onServerMessage(channel, type, arg)
{
    log("<< ---- Recieve message from TServer : " + "(channel " + channel + ")" + type);

    // All message from server should be redirected to add-on or page scripts.
    // So, just redirect it to add-on is ok, add-on will do the rest.
    self.port.emit('hub', channel, type, arg);
}

function onHubMessage(channel, type, arg)
{
    // All message from add-on should be redirect to TServer
    TServer.send(channel, type, arg);
}

function onLogMessage(msg)
{
    myLog(msg);
}

// ------------------------
// Helper functions
// ------------------------

function stringify(obj)
{
    if (typeof obj === "object")
        return JSON.stringify(obj);
    else
        return obj.toString();
}
function myLog(arg)
{
    document.body.lastChild.textContent = stringify(arg) + "\n\n" + document.body.lastChild.textContent;
}
